<template>
  <BaseDialog
    :visible="visible"
    :title="isEdit ? '编辑用户' : '新增用户'"
    width="600px"
    @update:visible="handleUpdateVisible"
    @confirm="handleConfirm"
    @cancel="handleCancel"
    :confirm-loading="loading"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      size="default"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="角色" prop="role">
            <el-select
              v-model="formData.roleId"
              placeholder="请选择角色"
              style="width: 100%"
            >
              <el-option
                v-for="role in props.roleList"
                :key="role.roleId"
                :label="role.name || role.roleName"
                :value="role.roleId"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="姓名" prop="name">
            <el-input
              v-model="formData.name"
              placeholder="请输入姓名"
              :disabled="shouldDisableFields || isAdmin"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="邮箱" prop="eMail">
            <el-input
              v-model="formData.eMail"
              placeholder="请输入邮箱"
              :disabled="shouldDisableFields"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model="formData.phone"
              placeholder="请输入手机号"
              :disabled="shouldDisableFields"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" v-if="!isEdit">
        <el-col :span="12">
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="formData.password"
              type="password"
              placeholder="请输入密码"
              show-password
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="确认密码" prop="confirmPassword">
            <el-input
              v-model="formData.confirmPassword"
              type="password"
              placeholder="请再次输入密码"
              show-password
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="所属部门" prop="department">
            <OrganizeTreeSelect
              v-model="formData.orgId"
              placeholder="请选择部门"
              @change="handleDepartmentChange"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="允许登录" prop="isEnable">
        <el-switch :disabled="isAdmin"
          v-model="formData.isEnable"
          active-text="启用"
          inactive-text="禁用"
        />
      </el-form-item>

    </el-form>
  </BaseDialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElRow, ElCol, ElSwitch } from 'element-plus'
import BaseDialog from '@/components/BaseDialog.vue'
import OrganizeTreeSelect from '@/components/OrganizeTreeSelect.vue'
import { useUserStore } from '@/stores/user'
import { useAuthStore } from '@/stores/auth'
import { error } from '@/utils/toast'
import type { User, OrganizeTreeNode } from '@/types'
import { encryptPassword } from '@/utils/crypto'

// Props
interface Props {
  visible: boolean
  userData?: User | null
  organizeId?: number
  roleList?: any[]
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  userData: null,
  organizeId: 0,
  roleList: () => []
})

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'success': []
}>()

// 使用stores
const userStore = useUserStore()
const authStore = useAuthStore()

// 响应式数据
const formRef = ref<InstanceType<typeof ElForm>>()

// 表单数据
const formData = reactive({
  name: '',
  eMail: '',
  phone: '',
  password: '',
  confirmPassword: '',
  department: '',
  isEnable: true,
  roleId: 0,
  role: '', // 前端显示用的角色名称
  orgId: 0
})

// 表单验证规则
const formRules = computed(() => ({
  name: shouldDisableFields.value ? [] : [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  eMail: shouldDisableFields.value ? [] : [
    { type: 'email' as const, message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: shouldDisableFields.value ? [] : [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    {
      validator: (_rule: any, value: string, callback: Function) => {
        if (value !== formData.password) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  orgId: [
    { required: true, message: '请选择部门', trigger: 'change' }
  ],
  isEnable: [
    { required: true, message: '请选择用户状态', trigger: 'change' }
  ],
  roleId: [
    { required: true, message: '请选择角色', trigger: 'change' }
  ]
}))

// 计算属性
const isEdit = computed(() => !!props.userData)
const loading = computed(() => userStore.loading)
// 判断是否为当前登录用户
const isCurrentUser = computed(() => {
  if (!props.userData || !authStore.user) return false
  return props.userData.id.toString() === authStore.user.id.toString()
})
// 判断是否应该禁用某些字段（非当前登录用户时禁用）
const shouldDisableFields = computed(() => isEdit.value && !isCurrentUser.value)

const isAdmin = computed(() => props.userData?.id === 1)
// 监听visible变化
watch(() => props.visible, (newVal) => {
  if (newVal) {
    initForm()
  }
})

// 监听userData变化
watch(() => props.userData, (newVal) => {
  if (newVal && props.visible) {
    initForm()
  }
})

// 方法
const initForm = () => {
  if (props.userData) {
    // 编辑模式
    Object.assign(formData, {
      name: props.userData.name || '',
      eMail: props.userData.eMail || '',
      phone: props.userData.phone || '',
      password: props.userData.password || '', // 保持原有密码
      confirmPassword: '',
      isEnable: props.userData.isEnable !== undefined ? props.userData.isEnable : true,
      roleId: props.userData.roleId || 0,
      orgId: props.userData.orgId || props.organizeId || 0
    })
  } else {
    // 新增模式
    Object.assign(formData, {
      name: '',
      eMail: '',
      phone: '',
      password: '',
      confirmPassword: '',
      isEnable: true,
      roleId: null,
      orgId: props.organizeId || 0
    })
  }
  
  // 清除验证
  nextTick(() => {
    formRef.value?.clearValidate()
  })
}

// 部门选项已经在store中管理，无需单独加载

const handleUpdateVisible = (value: boolean) => {
  emit('update:visible', value)
}

const handleCancel = () => {
  emit('update:visible', false)
}

const handleDepartmentChange = (_value: number | undefined, node: OrganizeTreeNode | null) => {
  // 可以在这里处理部门变化后的逻辑
  // 比如更新表单中的部门名称等
  if (node) {
    formData.department = node.name
  } else {
    formData.department = ''
  }
}

const handleConfirm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    const submitData = {
      ...formData,
      orgId: formData.orgId || props.organizeId || 0
    }
    
    // 删除不需要的字段
    delete (submitData as any).confirmPassword
    delete (submitData as any).role // 删除前端显示用的角色名称
    delete (submitData as any).department // 删除前端显示用的部门名称
    
    if (isEdit.value && props.userData) {
      // 编辑模式：添加用户ID
      (submitData as any).id = props.userData.id
      await userStore.updateUserAction(submitData)
    } else {
      submitData.password = encryptPassword(submitData.password)
      await userStore.createUserAction(submitData)
    }
    
    emit('success')
    emit('update:visible', false)
  } catch (err) {
    if (err !== false) { // 表单验证失败时err为false
      error('操作失败')
    }
  }
}
</script>

<style scoped lang="scss">
:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input__wrapper) {
  border-radius: 4px;
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 4px;
}
</style>
